package com.foreknow.test;

import com.foreknow.bean.Admin;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * Jdbc
 */
public class DBUtil {
    public static void main(String[] args) {
        try {
            //1.加载驱动
            Class.forName("com.mysql.jdbc.Driver");
            //2.获取连接
            Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/hr_systemdb?useUnicode=true&characterEncoding=utf8","root","123456");

            //3.获取到PreparedStatement对象 创建一个 PreparedStatement 对象来将参数化的 SQL 语句发送到数据库。
            // insert into admin（username,password,age,shcool,phone） values （?,?,?,?,?）;
            // update  delete
            PreparedStatement pstmt =  connection.prepareStatement("select * from admin where username=? and password=?");
            //将？替换为具体的值  setString(第几个？,具体的值)
            pstmt.setString(1,"tom");
            pstmt.setString(2,"123456");
            //执行查询
            ResultSet rs = pstmt.executeQuery();
            //遍历结果集
            List<Admin> list = new ArrayList<Admin>();
            while (rs.next()){
                //获取到当前行列的值
                String username = rs.getString("username");
                String password = rs.getString("password");
                System.out.println(username+"------"+password);
                //要将获取到的数据以对象的方式保存到List集合中
                Admin admin = new Admin();
                admin.setUsername(username);
                admin.setPassword(password);
                list.add(admin);
            }
            //遍历List集合中的数据
            for (Admin admin:list) {
                System.out.println(admin.getUsername()+"-----"+admin.getPassword());
            }

            for(int i = 0;i<list.size();i++){
                Admin admin = list.get(i);
                System.out.println(admin.getUsername()+"-----"+admin.getPassword());
            }

            //关闭资源
            rs.close();
            pstmt.close();
            connection.close();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
